<!Doctype html>

<head>
    <title>前台</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, user-scalable=no" />
    <style>
    .mods {
        background: #f5f5f5;
        margin: 1.5%;
        width: 30%;
        float: left;
        min-height: 100px;
    }

    .mods>h4 {
        background: rgb(54, 107, 255);
        color: #eee;
        margin: 0;
        padding: 4px 10px;
    }

    .mods>a {
        padding: 10px ;
    }
    </style>
</head>

<body>
    <div id="main">
        <div class="banner"></div>
        <div class="content" id="main-content">
        </div>
    </div>
    <script id="tpl-mods" type="html/template">
        <div class="mods">
            <h4>{{$modname}}</h4>
{{foreach from=data item=item}}            <a href="/news/{{item.id}}"><li>{{item.title}}</li></a>{{/foreach}}
        </div>
    </script>
    <script>
        var app = {};
        app.loadData = function (url, fn) {
            var xhr = new XMLHttpRequest(); console.log(xhr);
            xhr.open('GET', url);
            xhr.send();
            xhr.onload = function () {
                if (this.status == 200) {
                    data = JSON.parse(this.responseText);
                    data = data.data;
                    fn(data);
                } else {
                    alert('网络错误');
                }
            }
        }
        app.renderContent = function (data) {
            var reg_var = /{{(.*?)}}/g;
            var tpl = document.getElementById('tpl-mods').innerHTML;
            var html = data.map(function (val) {
                console.log(val)
                return tpl.replace("{{$modname}}", val.modname)
                    .replace(/{{foreach.*?}}(.*?){{\/foreach}}/, function (aa, bb) {
                        return val.data.map(function (item) {
                            return bb.replace(reg_var, function (cc, dd) {
                                return eval(dd);
                            });
                        }).join("\n");
                    });
            }).join("\n");
            console.log(html);
            document.getElementById("main-content").innerHTML = html;
        }
        var url = '/index-data';
        app.loadData(url, function (data) {
            app.renderContent(data);
        });
    </script>
</body>

</html>
